package utils;

import android.os.Build;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/10/12
 * Email: vhly@163.com
 */

public final class HttpTools {

    //手机版本号
    public static final String USER_AGENT = "ting_4.1.7(" + Build.MODEL + "," + Build.VERSION.SDK_INT + ")";

    private HttpTools() {}

    public static final int CONNECT_TIMEOUT = 5000 ;
    public static final int READ_TIMEOUT = 10000 ;
    public static byte[] doGet(String url) {
        byte[] ret = null;

        if (url != null) {

            HttpURLConnection conn = null;

            try {
                URL u = new URL(url);
                conn = (HttpURLConnection) u.openConnection();

                //设置连接的配置

                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(READ_TIMEOUT);

                conn.setRequestMethod("GET");

                //完善 HTTP 请求 的 内容
                //1.设定通用的 Http 头部信息

                //设定 Accept 头信息，告诉服务器客户端能接受什么数据
                conn.setRequestProperty("Accept","application/*,text/*,image/*,*/*");

                //设置接受的内容压缩算法
                conn.setRequestProperty("Accept-Encoding","gzip");

                //设置 user-agent
                conn.setRequestProperty("User-Agent", USER_AGENT);

                conn.connect();
                int code = conn.getResponseCode();
                if (code == 200) {
                    // TODO 给 data 赋值
                    InputStream fin = null;
                    try {
                        fin = conn.getInputStream();

                        // TODO: 2015/10/20 进行网络输入流的GZIP压缩

                        String encoding = conn.getHeaderField("Content-Encoding");

                        if ("gzip".equals(encoding)){
                            fin = new GZIPInputStream(fin) ;
                        }

                        ret = StreamUtil.readStream(fin);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        StreamUtil.close(fin);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                StreamUtil.close(conn);
            }

        }

        return ret;
    }

    /**
     * 执行post请求
     * @param url
     * @param map
     */
    public static void doPost(String url, HashMap<String, String> map) throws UnsupportedEncodingException {

        if (url != null) {

            //把药提交的数据组织起来
            StringBuilder sb = new StringBuilder();

            for (Map.Entry<String, String> en : map.entrySet()) {
                sb.append(en.getKey())
                        .append("=")
                        .append(URLEncoder.encode(en.getValue(), "utf-8"));
            }


            HttpURLConnection connection = null;

            try {
                URL u = new URL(url);
                connection = (HttpURLConnection) u.openConnection();

                //基本设置
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);
                connection.setDoOutput(true);
                connection.setDoInput(true);

                //设置提交的数据的类型
                connection.setRequestProperty("Content-Type", "application/x-www-from-urlencoded");
                connection.connect();

                //设置提交的数据
                byte[] b = sb.toString().getBytes();

                //提交数据，向服务端写入数据
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(b, 0, b.length);
                outputStream.close();

                InputStream in = null;
                if (connection.getResponseCode() == 200) {
                    in = connection.getInputStream();
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
